﻿// ActionScript file
/**
 * @author	:com.nickro
 * 
 * @Problems	:
 * 			对各个过程进行整理,creationChildren,updateLayout,dispatchEvent,等等
 */
package org.nickro.controls{
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class BaseControls extends Sprite{
		private var changed:Boolean=false;
		private var created:Boolean=false;
		protected var data:Object;
		protected var itemNumber:Number;
		public function BaseControls(dataProvider:Object=null){
			dataType(dataProvider);
			initialize();
		}
		private function dataType(obj:Object):void{
			if(obj != null){
				try{
					if(obj is Array){
						data = obj as Array;
						itemNumber=data.length;
					}
					
					if(obj is XMLList){
						data = obj as XMLList;
						itemNumber=data.length();
					}
	
					
					if(obj is XML){
						data = obj as XML;
						itemNumber= data.length();
					}
				}catch( e:TypeError){
					throw new TypeError("'dataProvider'的类型不正确");
				}
			}
		}
		private function initialize():void{
			addEventListener(Event.ADDED_TO_STAGE,onAdded);
			addEventListener(Event.REMOVED_FROM_STAGE,onRemoved);
		}
		protected function hasChanged():Boolean{
			return changed;
		}
		protected function setChanged():void{
			changed=true;
			if(hasChanged()){
				requestUpdate();
			}
		}
		
		private function requestUpdate():void{
			if(this.stage!= null){
				this.stage.invalidate();
			}
		}
		private function update():void{
			if (hasChanged())
			{
				updateDislayObject();
			}
		}
		//创建子项
		protected function createChildren():void{
			
		}
		//更新子项布局
		protected function updateDislayObject():void{
			createChildren();
		}
		
		//渲染场景
		//注意:更新时同时更新updateDisplayObject和mesure
		private function onRender(e:Event):void{
			if(hasChanged()){
				update();
			}
		}
		private function onAdded(e:Event):void{
			stage.addEventListener(Event.RENDER,onRender);
		}
		private function onRemoved(e:Event):void{
			stage.removeEventListener(Event.RENDER,onRender);
		}
		//数据的获取
		public function set dataProvider(value:Object):void
		{
			dataType(value);
		}
		
		public function get dataProvider():Object{
			return data;
		}
		
	}
}